AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
AddCSLuaFile( 'hud/cl_hud.lua' )
AddCSLuaFile( 'hud/cl_good_hud.lua' )
AddCSLuaFile( 'menu/cl_menu.lua' )
AddCSLuaFile( 'menu/cl_menu_toptimes.lua' )
AddCSLuaFile( 'menu/cl_menu_admin.lua' )
AddCSLuaFile( 'menu/cl_menu_splash.lua' )
AddCSLuaFile( 'menu/cl_menu_help.lua' )

resource.AddFile( "materials/mgui/sr-splash.vtf" )
resource.AddFile( "materials/mgui/sr-splash.vmt" )

include( 'shared.lua' )
include( 'race/sr_zone_control.lua' )
include( 'race/sr_race_timer.lua' )
include( 'race/sr_spawn_scoreboard.lua' )
include( 'race/sr_scheduler.lua' )

function GM:Initialize()

    print("===========SpaceRace Initialising===========")
    register_concommands()
    
    loadTimes()
    
    scheduler:Start()
    
    --CreateConVar("sr_debug", "1",  FCVAR_NOTIFY | FCVAR_ARCHIVE | FCVAR_REPLICATED)
    createConvars()

end

function createConvars()
    
    // Load the config file
    print("==========Loading SpaceRace Convars=========")
    --local FileName ="../cfg/spacerace.cfg"
    --local FileName ="../cfg/spacerace.txt"
    local FileName ="SpaceRace/spacerace_cfg.txt"
    local Settings = {}
    
    if file.Exists(FileName) then
        local f = file.Read(FileName)
        
        status, error = pcall(
                function()
                    print("==========Decoding SpaceRace Convars========")
                    Settings = glon.decode( f )
                end
            )
        
        if status then
            print("==========Printing SpaceRace Convars========")
            PrintTable(Settings)
        else
            print( status, error )
            ErrorNoHalt("SpaceRace Convar Decoding Error: "..error)
        end
     
        // Create the convars if they don't already exist
        print("==========Setting SpaceRace Convars=========")
        for k, v in pairs( Settings ) do
            if !ConVarExists( k ) then
                CreateConVar( k, v, FCVAR_NOTIFY )
                print("SR: CVar " .. k .. " = " .. v)
            end
        end
    else
        
        Settings["sr_debug"] = 1
        Settings["sr_wait_time"] = 20
        Settings["sr_race_time"] = 60

        file.Write(FileName, glon.encode(Settings))
        print("============Settings file created============")
        print("SR: Settings file: " .. FileName)
    end

end

function setDebug(ply, command, args)
    if ply:IsAdmin() then
        local value = tonumber(args[1])

        if !value then
            value = GetConVarNumber("sr_debug") == 1 and 0 or 1 --set to the opposite of current setting if no args passed
        end

        game.ConsoleCommand("sr_debug " .. value .. "\n")
    else
        print("SR: "..ply:Nick().." attempted to set debug level to " .. value)
    end
end
concommand.Add("sr_set_debug",setDebug,{0,1})

function loadTimes()

    local MapName = game.GetMap()
    local FileName = "SpaceRace/BestTimes/"..MapName.."_Times.txt"
    
    if file.Exists(FileName) then
            TimesTable = util.KeyValuesToTable(file.Read(FileName))
            print("==============Times file loaded=============")
            print("=============="..table.Count(TimesTable).." times loaded=============")
            PrintTable(TimesTable);
    else
            TimesTable = {}
            file.Write(FileName, util.TableToKeyValues(TimesTable))
            print("=============Times file created============")
    end    
end

function findMapEnts()
    local spawns = ents.FindByClass( "func_spacerace" )
    print("======= "..#spawns.." SpaceRace Triggers Found =========")
    local checkpoints = 0
    for k,v in pairs (spawns) do
        if v:IsCheckpoint() then checkpoints = checkpoints + 1 end
    end
    print("====== "..checkpoints.." SpaceRace Checkpoints Found =======")
    
    SetGlobalInt ( "checkpoints", checkpoints )
    
    scheduler:FindDoors()
end
hook.Add("InitPostEntity", "findMapEnts", findMapEnts)

function GM:PlayerSpawn( ply )  //What happens when the player spawns
 
    self.BaseClass:PlayerSpawn( ply )   
 
    ply:SetGravity( 1.0 )  
    ply:SetMaxHealth( 100, true )  
 
    ply:SetWalkSpeed( 250 )  
    ply:SetRunSpeed( 400 )
    
    --ply:ConCommand( "sr_menu" )
 
end

function GM:PlayerInitialSpawn( ply )  // When spawning after joining the sever

	//if ply:IsAdmin() then
	//	spawn_team_admin( ply )
	//else
            joining( ply )
            spawn_team_spectator( ply )
	//end
        
        // Notify of new player
	for k,v in pairs(player.GetAll()) do
		v:PrintMessage( HUD_PRINTTALK , "[SpaceRace] " .. ply:Nick() .. " has arrived.")
	end
        
        print("[SpaceRace] " .. ply:Nick() .. " has arrived.")
        
        ply:ConCommand( "sr_menu" )
end

function GM:PlayerSelectSpawn( ply )
 
    local spawntype = "info_player_start"
 
    --if ply:Team() == TEAM_SPECTATOR then
    --    spawntype = "info_player_rebel"
    
    --elseif ply:Team() == TEAM_BLUE then
    --    spawntype = "info_player_combine"
    --end
 
    --local spawns = ents.FindByClass( "info_player_start" )
    local spawns = ents.FindByClass( spawntype )
    local random_entry = math.random(#spawns)
 
    return spawns[random_entry]
 
end

function GM:PlayerLoadout( ply ) // What should the player recieve when joining a team?

    SetPlayerLoadout( ply )

end

function GM:PlayerAuthed( ply, SteamID, UniqueID )  
  
    //  
    // PData uses the player's uniqueid, so we fill in their wins   
    //  after they have definitiely have a SteamID  
    //  
    local MapName = game.GetMap()
    
    --ply.BestTime = ply:GetPData( MapName.."_BestTime", "0" )
    local ID = string.lower(string.Replace(ply:SteamID(),":","_"))
    ply.BestTime =  TimesTable[ID] or 0
    if ply.BestTime != 0 then
        print("SR PlayerAuthed, Best Time Found: "..ply.BestTime)
    end
    ply:SetNetworkedFloat( "BestTime", ply.BestTime )
    
    --if SR_DEBUG then print("SR PlayerAuthed: "..ply:Nick().." Best: "..ply.BestTime) end
    
    if GetConVarNumber("sr_debug") == 1 then print("SR PlayerAuthed: "..ply:Nick().." Best: "..ply.BestTime) end
    
    ply.RaceStart = 0
    ply.RaceFinish = 0
    ply.RaceTime = 0
    
    --SpawnScoreboard()

end



// ---------------------------------------------------------------------------

function CanPlayerSpawnObject( ply )
    if ply:Team() != TEAM_BUILDER then
        ply:PrintMessage( HUD_PRINTTALK, "[SpaceRace] Props can only be spawned in the build area.")
        return false
    end
    return true
end

hook.Add("PlayerSpawnObject","CanPlayerSpawnObject", CanPlayerSpawnObject)

function joining( ply )
 
	ply:Spectate( 5 )
	ply:SetTeam( TEAM_JOINING )
end

function GM:PlayerNoclip( ply )
	if ply:IsSuperAdmin()--[[if the player is a superadmin, the player is recognized by the script.]] then
		return true
	else
		return false
	end
end